#include <assert.h>
#include "epoll.h"
#include "tcp.h"

void DoAccept(Epoll& ep, Tcp& ls, struct epoll_event& e)
{
	Socket ws;
	if( EPOLLIN & e.events )
	{
		assert( ls.Accept(ws) );
		assert( ep.AddEvent(ws.GetSocket(), EPOLLIN) );
	}
	printf("work(%d)\n", ws.GetSocket());
}
void DoReadWrite(Epoll& ep, struct epoll_event& e)
{
	Socket work;
	char buf[1024] = {0};
	int len = sizeof(buf);

	work.SetSocket( e.data.fd );
	if( EPOLLIN & e.events )
	{
		len = work.Recv(buf, len);
		if( len > 0 )
		{
			buf[ len ] = 0;
			printf("buf(%s)=%d\n", buf, len);
		}
		else
		{
			ep.DelEvent(e.data.fd, EPOLLIN | EPOLLOUT);
			work.Close();
		}
	}
	if( EPOLLPRI & e.events )
	{
		work.RecvOob(buf, len);
	}
	if( EPOLLHUP & e.events )
	{
		ep.DelEvent(e.data.fd, EPOLLIN | EPOLLOUT);
		work.Close();
	}
}
int main(void)
{
	Tcp ls;
	Epoll ep;

	ls.ReuseAddress(true);
	ls.Bind("0.0.0.0", 10000);
	ls.Listen(100);
	printf("lisent(%d)\n", ls.GetSocket());

	assert( ep.Open(100) );
	assert( ep.AddEvent(ls.GetSocket(), EPOLLIN) );

	while(1)
	{
		int count = ep.WaitEvent(1);
		for(int i = 0; i < count; i++)
		{
			struct epoll_event &e = ep[i];
			if( ls.GetSocket() == e.data.fd )
			{
				DoAccept(ep, ls, e);
			}
			else
			{
				DoReadWrite(ep, e);
			}
		}
		usleep(100);
	}

	return 0;
}
